package com.csun.dsms.utils;

import cn.hutool.core.util.StrUtil;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExcelUtils {

    public InputStream replaceExcel(InputStream inputStream, Map<String, Object> params) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            Workbook wb = WorkbookFactory.create(inputStream);

            Sheet sheet = wb.getSheetAt(0);
            int trLength = sheet.getLastRowNum();
            for (int i = 0; i < trLength; i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                int minColIx = row.getFirstCellNum();
                int maxColIx = row.getLastCellNum();
                for (int colIx = minColIx; colIx < maxColIx; colIx++) {
                    Cell cell = row.getCell(colIx);
                    if (cell == null) {
                        continue;
                    }
                    String runText = "";
                    try {
                        runText = cell.getStringCellValue();
                    } catch (Exception e) {
                        continue;
                    }
                    if (runText.equals("")) {
                        continue;
                    }

                    Matcher matcher = this.matcher(runText);
                    if (matcher.find()) {
                        while ((matcher = this.matcher(runText)).find()) {
                            runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))));
                        }
                        if (StrUtil.isEmpty(runText) || runText.equals("null")){
                            runText = "";
                        }
                        cell.setCellValue(runText);
                    }
                }
            }
            wb.write(outputStream);
            return new ByteArrayInputStream(outputStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 正则匹配字符串
     * @param str
     * @return
     */
    private Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }

}
